package com.mingyuean.demo.learn;

import com.mingyuean.demo.test.User;
import com.mingyuean.demo.test.UserMapper;
import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author MingYueAn
 * <p>  JDK动态代理
 * <p>  2023/3/20 11:18
 * @version: 1.0
 */
public class newProxyInstanceLearn {
    @Test
    public void name() {
        // 定义被代理的对象实例为 UserMapper 类的 Class 对象
        final Class<UserMapper> userMapperClass = UserMapper.class;

        // 代理模式：https://blog.csdn.net/Passer_hua/article/details/122617628
        /* 代理模式：JDK动态代理 */
        //newProxyInstance: 创建代理对象
        //Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler handler)
        // loader: 被代理类对象
        // interfaces：接口类对象，被代理对象所实现的接口数组
        // handler：调用处理器，被调用对象的那个方法被调用后该如何处理
        final Object newProxyInstance = Proxy.newProxyInstance(
                ClassLoader.getSystemClassLoader(),
                new Class[]{userMapperClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        final String name = method.getName();
                        System.out.println("name = " + name);
                        System.out.println("Arrays.toString(args) = " + Arrays.toString(args));
                        return proxy;
                    }
                }
        );

        // 强制转换
        UserMapper userMapper = (UserMapper) newProxyInstance;
        // 调用 UserMapper 接口的 findUserByUsernamePassword() 方法，并输出结果
        final User byUsernamePassword = userMapper.findUserByUsernamePassword("1", "张三");
        System.out.println("byUsernamePassword = " + byUsernamePassword);
    }
}
